
from fastapi import Request
from pydantic import BaseModel
from tortoise.transactions import atomic, in_transaction

from service import UserService, BookService
from service import RepositoryService
from common.result.Result import Result
from common.enum import BaseEnum
from util.str import Str
from util.log import Log
from util.token import Token
from util.time import Time

async def GetRepositoryList(req: Request, body: dict = None):
    try:
        token = req.headers.get("token")
        if Str.isBlank(token):
            Log.error('参数为空，检查参数')
            return Result.error(BaseEnum.PARAMETER_INVALID_ERROR)
        
        user = await UserService.getUserByToken(token)
        if user == None:
            Log.error('user 不存在', user)
            return Result.error(BaseEnum.USER_NOT_EXISTS_ERROR)
        Log.debug('user id', user.id)

        # 获取仓库列表
        repositoryList = await RepositoryService.getRepositoryListByUserId(user.id)

        # 构造 最近编辑文档 列表
        res = []
        for item in repositoryList:
            # 最近 3 个
            recentEditBooks = await BookService.getRecentEditBookListByRepositoryId(item.id, 3)
            tmp = dict(item)
            tmp.update({
                "recentEditBooks": recentEditBooks
            })
            res.append(tmp)
        
        return Result.success(res)
    except Exception as e:
        Log.error('创建知识库异常', e)
        return Result.error(BaseEnum.SERVICE_ERROR)


